import { DataStorage } from '@/utils/storage'

const store = new DataStorage('auth', localStorage)

export interface Token {
  tokenType?: string
  accessToken: string
  refreshToken?: string
}

interface TokenData {
  tt?: string
  t: string
  r?: string
}

export const isLogin = () => !!getToken()

export const setToken = (token?: Token) => {
  if (token) {
    store.set('token', {
      tt: token.tokenType,
      t: token.accessToken,
      r: token.refreshToken,
    })
  } else {
    store.remove('token')
  }
}

export const getToken = (): Token | null => {
  const token = store.get<TokenData>('token')
  if (!token) return null
  if (!token.t) return null
  return { tokenType: token.tt, accessToken: token.t, refreshToken: token.r }
}

export const clearToken = () => {
  setToken()
}
